<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <!-- 警告 -->
      <el-alert title="注意:只允许为第三级分类设置相关参数!" type="warning" show-icon>
      </el-alert>
      <div class="chios">
        选择商品分类: <el-cascader v-model="typeArr" :options="options" @change="chgCascader"
          :props="{ expandTrigger: 'hover', label: 'cat_name', value: 'cat_id' }"></el-cascader>
      </div>

      <el-tabs v-model="activeName" @tab-click="tabClick">
        <el-tab-pane label="动态参数" name="many">
          <!-- 按钮 -->
          <el-button :disabled="typeArr.length !== 3" type="primary" size="mini"
            @click='dialogManyVisible = true'>添加参数</el-button>
          <!-- 表格 -->
          <el-table border style="width: 100%" :data="tableDataMany">
            <el-table-column type="expand" width="80">
              <!-- 作用域插槽，获取一行的数据 -->
              <template slot-scope="scope">
                <div>
                  <!-- close标签的关闭的是偶 -->
                  <el-tag @close="handleTagClose(scope.row, i)" v-for="(tag, i) in scope.row.attr_arr" :key="i" closable>
                    {{ tag }}
                  </el-tag>
                  <!-- @keyup.enter.native="handleInputConfirm"   -->
                  <el-input class="input-new-tag" v-model="inputValue" v-if="scope.row.inputVisible" size="small"
                    ref="saveTagInput" @blur="handleInputConfirm(scope.row)">
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New
                    Tag</el-button>
                </div>
              </template>
            </el-table-column>
            <!-- type="index" 使用序号 -->
            <el-table-column type="index" width="80">
            </el-table-column>
            <el-table-column prop="attr_name" label="参数名">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <div>
                  <!-- 修改 -->
                  <el-button type="primary" icon="el-icon-edit" size="mini"
                    @click="getCateAttrRow(scope.row)"></el-button>
                  <!-- 删除 -->
                  <el-button type="danger" icon="el-icon-delete" size="mini"
                    @click="delCateAttrById(scope.row.cat_id, scope.row.attr_id)"></el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态数据 -->
        <el-tab-pane label="静态属性" name="only">

          <el-button :disabled="typeArr.length !== 3" type="primary" size="mini">添加参数</el-button>

          <el-table border stripe :data="tableDataOnly" style="width: 100%">
            <el-table-column type="expand" width="80">
              <template slot-scope="scope">
                <div>
                  <!-- close标签的关闭的是偶 -->
                  <el-tag @close="handleTagClose(scope.row, i)" v-for="(tag, i) in scope.row.attr_arr" :key="i" closable>
                    {{ tag }}
                  </el-tag>
                  <!-- @keyup.enter.native="handleInputConfirm"   -->
                  <el-input class="input-new-tag" v-model="inputValue" v-if="scope.row.inputVisible" size="small"
                    ref="saveTagInput" @blur="handleInputConfirm(scope.row)">
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New
                    Tag</el-button>
                </div>
              </template>
            </el-table-column>
            <el-table-column type="index" width="80">
            </el-table-column>
            <el-table-column prop="attr_name" label="属性名">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <div>
                  <!-- 修改 -->
                  <el-button type="primary" icon="el-icon-edit" size="mini"></el-button>
                  <!-- 删除 -->
                  <el-button type="danger" icon="el-icon-delete" size="mini"
                    @click="delCateAttrById(scope.row.cat_id, scope.row.attr_id)"></el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- dialogManyVisible true来控制dialog的显示 -->
    <el-dialog :title="`${addManyForm.cat_id ? '修改' : '添加'}动态参数`" :visible.sync="dialogManyVisible" width="50%">
      <el-form ref="addManyForm" :model="addManyForm" :rules="addManyRules" label-width="100px">
        <el-form-item label="动态参数" prop="attr_name">
          <el-input v-model="addManyForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogManyVisible = false">取 消</el-button>
        <el-button v-if="addManyForm.cat_id" type="primary" @click="updateCateAttrRow">确 定</el-button>
        <el-button v-else type="primary" @click="addCateAttr">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request';
export default {
  data () {
    return {
      activeName: "many",
      // 级联数据
      options: [],
      // 分类参数id数组
      typeArr: [],
      // 动态属性列表
      tableDataMany: [],
      // 控制对话框的显示
      dialogManyVisible: false,
      // 动态参数表单
      addManyForm: {
        attr_name: '',
        attr_sel: ''
      },
      // 校验的数组
      addManyRules: {
        attr_name: [{ required: true, message: '请输入动态参数', trigger: 'blur' }]
      },
      // 接收输入框的数据
      inputValue: '',
      // 动态属性列表
      tableDataOnly: []
    }
  },
  mounted () {
    this.getCategoriesCascader()
  },
  methods: {
    // 获取级联数据,分类数据
    async getCategoriesCascader () {
      const { data: { data, meta } } = await request({
        url: "categories",
        method: "GET"
      })
      if (meta.status !== 200) {
        return this.$message.error("获取参数错误")
      }
      this.options = data
      // console.log(data, meta);
    },
    chgCascader (val) {
      if (val.length !== 3) {
        this.typeArr = []
        return
      }
      // 获取参数
      this.getCategoriesAttributes()
    },
    // 根据id获取动态|静态的列表
    async getCategoriesAttributes () {
      const { data: { data, meta } } = await request({
        url: `categories/${this.typeArr[2]}/attributes`,
        params: { sel: this.activeName },
        method: "get"
      })
      if (meta.status !== 200) {
        return this.$message.error("获取分类参数失败")
      }
      // data[0].attr_vals       // 在赋值之前,需要转化数据
      data.forEach(obj => {
        // 控制输入框是否显示的
        obj.inputVisible = false
        // 转化好的数据重复绑定到 属性
        if (obj.attr_vals.trim() === "") {
          // 重新添加的数据
          obj.attr_arr = []
        } else {
          obj.attr_arr = obj.attr_vals.split(" ")
        }
      });
      if (this.activeName === "many") {
        this.tableDataMany = data
      } else {
        this.tableDataOnly = data
      }
    },
    // 标签页点击切换了

    tabClick () {
      // console.log("切换了", this.activeName);
      // 重新获取参数的列表数据| 动态|静态
      this.getCategoriesAttributes()
    },

    // 根据参数id和属性id来删除参数的属性
    delCateAttrById (cate_id, attr_id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 确定的按钮的时候删除数据
        const { data: { meta } } = await request({
          url: `categories/${cate_id}/attributes/${attr_id}`,
          method: "delete"
        })
        if (meta.status !== 200) {
          return this.$message.error("删除失败")
        }
        // 提示成功
        this.$message.success("删除成功")
        // 刷新页面
        this.getCategoriesAttributes()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 添加动态参数
    async addCateAttr () {
      // console.log(this.$refs);
      // 调用校验方法
      this.$refs.addManyForm.validate(async (valid) => {
        // valid==true 通过校验,
        if (!valid) {
          return this.$message.error("请填写正确数据")
        }
        this.addManyForm.attr_sel = this.activeName
        const { data: { meta } } = await request({
          url: `categories/${this.typeArr[2]}/attributes`,
          method: "POST",
          data: this.addManyForm
        })
        if (meta.status !== 201) {
          return this.$message.error("添加失败")
        }
        this.$message.success("添加成功")
        // 关闭对话框
        this.dialogManyVisible = false
        // 重新赋值
        this.addManyForm = this.$options.data().addManyForm
        // 刷新页面
        this.getCategoriesAttributes()
      })
    },
    // 当点击的时候显示input 输入框
    showInput (obj) {
      // 变成输入框
      obj.inputVisible = true
      // 让输入框获取光标,页面的数据,dom重新渲染,才会执行
      this.$nextTick(() => {
        this.$refs.saveTagInput.focus();
      })
      // setTimeout(() => {
      //   this.$refs.saveTagInput.focus();
      // }, 1000);
    },
    // 失去焦点的时候,重新变成按钮
    async handleInputConfirm (obj) {
      // console.log(obj);
      // 将input去掉
      obj.inputVisible = false
      // 如果是空的,立刻结束
      if (!this.inputValue) {
        return
      }
      obj.attr_arr.push(this.inputValue);
      this.inputValue = ""
      obj.attr_vals = obj.attr_arr.join(" ")
      const { data: { meta } } = await request({
        url: `categories/${obj.cat_id}/attributes/${obj.attr_id}`,
        // 修改的方法是put 查询|获取get ,添加post,删除 delete
        method: "PUT",
        data: obj
      })
      if (meta.status !== 200) {
        return this.$message.error("更新属性失败")
      }
      return this.$message.success("更新成功")
    },
    async handleTagClose (obj, i) {
      // 根据i 删除数组的数据
      obj.attr_arr.splice(i, 1)
      // 更新参数的属性
      this.updateCateAttr(obj)
    },
    // 更新参数的属性
    async updateCateAttr (obj) {
      obj.attr_vals = obj.attr_arr.join(" ")
      const { data: { meta } } = await request({
        url: `categories/${obj.cat_id}/attributes/${obj.attr_id}`,
        // 修改的方法是put 查询|获取get ,添加post,删除 delete
        method: "PUT",
        data: obj
      })
      if (meta.status !== 200) {
        return this.$message.error("更新属性失败")
      }
      return this.$message.success("更新成功")
    },
    // 获取到需要修改的数据
    getCateAttrRow (row) {
      // 将row的值给addManyForm
      this.addManyForm = row
      this.dialogManyVisible = true
    },
    // 更新数据
    updateCateAttrRow () {
      // console.log(this.addManyForm);
      this.updateCateAttr(this.addManyForm)
      this.dialogManyVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.box-card {
  margin-top: 20px;

  .chios {
    font-family: "宋体";
    font-style: oblique;
    margin-top: 10px;
    font-size: 20px;
  }

  .el-table {
    margin-top: 20px;

    .el-tag {
      margin: 10px;
    }
  }

  .input-new-tag {
    width: 90px;
    margin-left: 10px;
  }
}
</style>
